import { connect, mapProps } from '@formily/react';
import { inbiz } from '@inbiz/core';
import { getMessage, TextWidget } from '@inbiz/react';
import classNames from 'classnames';
import { forwardRef, ReactText, Ref, useEffect, useRef } from 'react';
import { IValue as IConfigModalValue } from '../../designer/components/configModal';
import { IValue as IBusinessData } from '../../designer/components/subtableConfigModal';
import api from './api';
import TableTransfer from './components/tableTransfer';
import TreeTransfer from './components/treeTransfer';
import './style.less';
import { getDocumentInfo } from './service';
import { combineTransfer } from '@inbiz/utils';
// import { useRequest } from '@umijs/hooks';
export interface TransferProps {
  /**
   * @description 设置统一样式前缀。注意：需要配合 less 变量 @inbiz-prefix 使用
   * @default     inbiz
   */
  prefixCls?: string;
  /**
   * @description 自定义类名
   */
  className?: string;
  /**
   * @description 待选框标题
   * @default     待选列表
   */
  leftTitle: string;
  /**
   * @description 已选框标题
   * @default     已选列表
   */
  rightTitle: string;
  /**
   * @description 是否显示分页器
   * @default     false
   */
  showPagination: boolean;
  /**
   * @description 每页条数。注意：仅当 showPagination 属性为 true 时才生效
   * @default     10
   */
  pageSize: number;
  /**
   * @description 是否显示搜索框
   * @default     false
   */
  showSearch: boolean;
  /**
   * @description 禁用
   * @default     false
   */
  readOnly?: boolean;
  /**
   * @description 禁用
   * @default     false
   */
  disabled?: boolean;
  /**
   * @description 指定选中项
   */
  value?: string[];
  /**
   * @description 容器高度
   */
  boxHeight?: string;
  /**
   * @description 自定义配置相关参数
   */
  configModalValue?: IConfigModalValue;
  /**
   * @description 子表存储相关参数
   */
  businessData?: IBusinessData;
  /**
   * @description 子表存储相关参数
   */
  storageConfig?: {
    business: string;
    tableData: {
      componentAttr: string;
      modelAttr: string;
    }[];
  };
  /**
   * @description 控件id
   */
  controlId: string;

  viewMode?:string;
  /**
  /**
   * @description 修改的控件的id
   */
  originValue: any;
  /**
   * @description 获取子表存储相关参数
   */
  getBusinessData?: (v?: IBusinessData) => void;
  /**
   * @description 选择完成后的回调
   */
  onChange?: (v: string[]) => void;
  sourceModel?: string;
  modelkey?: string;
  inbiz?: inbiz;
  callBackEvents?: {
    onParamFormat?: <T>(param: T) => T;
    onRequest?: (param: any) => Promise<any>;
    onData?: <T>(data: T) => T;
  };
  emit?: {
    (type: 'onload'): void;
    (type: 'onSuccess', arg: any): void;
    (type: 'onError'): void;
    (type: 'onSelectChange', sourceSelectedKeys: string[], targetSelectedKeys: string[]): void;
    (type: 'onSelect', arg: ReactText[], arg1: any[]): void;
  };
  modelname: string;
  searchPlaceholder: string;
}

export type IRef = Ref<ReturnType<typeof api>>;

const Transfer: EFC<TransferProps, any> = forwardRef((props: TransferProps, ref: IRef) => {
  // const {
  //   data: modelData = [],
  //   run: getModelDataAsync,
  // } = useRequest(getModelData, { manual: true });

  const {
    prefixCls = 'inbiz',
    className,
    showPagination,
    pageSize,
    showSearch,
    disabled,
    readOnly,
    value: propsValue = [], // 列表：[1, 16] // 树：["1-1-2-1","1-1-2-2"]
    configModalValue,
    businessData,
    sourceModel,
    modelkey,
    inbiz,
    callBackEvents,
    emit,
    getBusinessData,
    onChange,
    boxHeight,
    leftTitle,
    rightTitle,
    modelname,
    viewMode,
    ...restProps
  } = props;
  const value = propsValue || [];
  const { type, fieldOptions = [] } = configModalValue || {};
  const reqParams = {
    appId: inbiz?.appInfo.appId || '',
    id: configModalValue?.currentIdField || '',
    sourceKey: sourceModel || '',
    parentId: configModalValue?.parentIdField || '',
  };
  useEffect(() => {
    getBusinessData?.(businessData);
  }, [businessData]);

  // useEffect(() => {
  //   getModelDataAsync({ appId: reqParams.appId })
  // }, [])
  const renderTitle = (title: string) => {
    return (
      <div
        style={{
          color: 'var(--inbiz-color-text)',
          fontSize: 'var(--inbiz-font-size-base)',
        }}
      >
        <TextWidget>{title}</TextWidget>
      </div>
    );
  };

  const commonProps = {
    ...props,
    callBackEvents,
    emit,
    pRef: ref,
    targetKeys: propsValue || [],
    reqParams,
    disabled: readOnly || disabled,
    showSearch,
    fieldNames: {
      title: configModalValue?.labelField || '',
      children: 'child',
      key: configModalValue?.currentIdField || '',
      searchKey: configModalValue?.searchKey || '',
    },
    viewMode,
    modelName: modelname,
    className: classNames(`${prefixCls}-Transfer`, className),
    listStyle: { width: 'calc((100% - 104px)/2)', height: boxHeight, flex: 'none' },
    titles: [renderTitle(leftTitle || ''), renderTitle(rightTitle || '')],
    selectAllLabels: [
      ({ selectedCount, totalCount }: { selectedCount: number; totalCount: number }) =>
        `${selectedCount}/${totalCount}`,
      ({ selectedCount, totalCount }: { selectedCount: number; totalCount: number }) =>
        `${selectedCount}/${totalCount}`,
    ],
    onChange,
  };
  return (
    <div {...restProps} title="" style={{ marginBottom: 1 }} >
      {type === 'tree' && <TreeTransfer {...commonProps} />}
      {type === 'list' && (
        <TableTransfer
          {...commonProps}
          searchPlaceholder={props.searchPlaceholder}
          fieldOptions={fieldOptions}
          showPagination={showPagination}
          pageSize={showPagination ? pageSize ?? 10 : 20}
        />
      )}
    </div>
  );
});

Transfer.displayName = 'Transfer';

Transfer.originValueFormat = (value: string, props: any) => {
  return getDocumentInfo(value, props).then((res) => {
    if (props.childModelConfig) {
      let result = combineTransfer(props, res);
      return result.toString().split(",");
    }
    return res;
  });
};
export default connect(
  Transfer,
  mapProps({}, (props, field) => ({
    ...props,
    boxHeight: field.decoratorProps?.style?.height,
    searchPlaceholder: getMessage('Transfer.plaseEnterSearchContent'),
  })),
);
